/**
 * 多设备处理
 * MediaSourceTrack API 只有最新版的Chrome 支持
 */

function hasUserMedia() {
    return !!(navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia) ;
}

if(hasUserMedia()){
    navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia ;
    // 根据不同的浏览器 设置不同的分辨率和其他参数值
    var constraints = {
        video:{
            mandatory:{
                minWidth:640,
                maxHeight:480,
            }
        },audio:true
    }

    if(/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|OperaMini/i.test(navigator.userAgent)){
        // 用户正在使用移动设备，请降低我们的最小分辨率
        constraints ={
            video:{
                mandatory:{
                    minWidth:480,
                    minHeight:320,
                    maxWidth:1024,
                    maxHeight:768
                }
            },audio:true
        }
    }

/*    navigator.getUserMedia(
        constraints,function (stream) {
            var video = document.querySelector('video');
            video.src = window.URL.createObjectURL(stream);
        },function (erro) {
            console.log("Raise an error when capturing:",erro);
    }
    );*/

    // 通过MediaSourceTrack 请求列表从中选择我们所需要的设备

    MediaStreamTrack.getSources(function(sources) {
            var audioSource = null ;
            var videoSource = null ;
            for(var i=0 ; i< sources.length ; i++){
                var source = sources[i] ;
                if(source.kind === "audio"){
                    console.log("发现麦克风",source.label,source.id);
                    audioSource = source.id ;
                }else if(source.kind === "video"){
                    console.log("发现摄像头",source.label,source.id);
                    videoSource = source.id ;
                }else{
                    console.log("发现未知资源",source);
                }
            }
            var constraints = {
                audio:{
                    optional:[{sourceId:audioSource}]
                },
                video:{
                    optional:[{sourceId:videoSource}]
                }
            };
            navigator.getUserMedia(
                constraints,function (stream) {
                    var video = document.querySelector('video');
                    video.src = window.URL.createObjectURL(stream);
                },function (erro) {
                    console.log("Raise an error when capturing:",erro);
                });
        });
}else{
    alert('抱歉您的浏览器不支持');
}